import { login, logout, getInfo } from '@/api/user/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getUserRoleArry } from '@/utils/get-user-role'
import { completePermission, permissionByUser } from '@/api/permission/permission.js'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    id: '',
    roles: [],
    authority: [],
    fatherPower: [],
    imagePath: 'https://oss.95buff.com/'
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState()) // getDefaultState 赋值到 state
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_MOBILE: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  GET_AUTHORITY: (state, authority) => {
    state.authority = authority
  },
  GET_FATHERPOWER: (state, fatherPower) => {
    state.fatherPower = fatherPower
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    console.log('login111')
    const { username, password, code, fingerprint, longitudeAndLatitude } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: username.trim(), password, code, fingerprint, longitudeAndLatitude }).then(response => {
        const { data } = response
        if (data.success) {
          commit('SET_TOKEN', data.data)
          setToken(data.data)
          resolve()
        } else {
          reject(data.msg)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roleId, nickName, mobile, id } = data
        const roles = getUserRoleArry(roleId)
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles)
        commit('SET_NAME', nickName)
        commit('SET_MOBILE', mobile)
        commit('SET_ID', id)
        dispatch('getAuthority')
        dispatch('getFatherPower')
        resolve(roles)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
        location.reload()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // 权限相关全部id
  getAuthority({ commit, state }) {
    permissionByUser().then(res => {
      console.log(res.data,'0---2')
      commit('GET_AUTHORITY', res.data)
    })
  },

  // 子权限对应父级权限
  getFatherPower({ commit, state }) {
    let allPower = []
    let userPower = []
    completePermission().then(res => {
      allPower = res.data
      permissionByUser().then(res => {
        userPower = res.data
        let list = [] // 权限合集
        for (let i = 0; i < allPower.length; i++) {
          list = list.concat(allPower[i].permissionList)
        }
        const listData = [] // id所对应权限
        for (let k = 0; k < userPower.length; k++) {
          const itemData = list.find(item => item.id === userPower[k])
          if (itemData) {
            listData.push(itemData)
          }
        }

        // 去重
        function duplicateRemoval(arr) {
          const res = new Map()
          return arr.filter((item) => !res.has(item.parentId) && res.set(item.parentId, 1))
        }

        const parentData = duplicateRemoval(listData) // 权限所对应父级

        const parentIdData = [] // 父级id
        for (let k = 0; k < parentData.length; k++) {
          parentIdData.push(parentData[k].parentId)
        }
        commit('GET_FATHERPOWER', parentIdData)
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
